﻿namespace Graph;

public class BFSCycleDetection
{
    private IGraph G;
    private bool[] visited;
    private Queue<int> queue = new Queue<int>();

    private int[] pre;

    public bool HasCycle { get; private set; } = false;

    public BFSCycleDetection(IGraph G)
    {
        this.G = G;
        visited = new bool[G.V];
        pre = new int[G.V];
        for (int i = 0; i < pre.Length; i++)
            pre[i] = -1;

        for (int v = 0; v < G.V; v++)
        {
            if (!visited[v])
            {
                BFS(v);
            }                
        }
    }

    private void BFS(int s)
    {
        visited[s] = true;
        queue.Enqueue(s);

        while (queue.Count != 0)
        {
            int v = queue.Dequeue();

            foreach (int w in G.Adj(v))
            {
                if (!visited[w])
                {
                    pre[w] = v;
                    visited[w] = true;
                    queue.Enqueue(w);
                }
                else
                {
                    if (G is IDiGraph)
                    {
                        HasCycle = true;
                        return;
                    }
                    else
                    {
                        if (w != pre[v])
                        {
                            HasCycle = true;
                            return;
                        }
                    }
                }
            }
        }
    }

    //验证
    static void Main(string[] args)
    {
        //IGraph graph = new AdjLinkList("无向无权图/g3.txt");
        IDiGraph graph = new DiAdjLinkList("有向无权图/无权有环图.txt");
        Console.WriteLine(graph);
        BFSCycleDetection cycleDetection = new(graph);
        Console.WriteLine(cycleDetection.HasCycle);

        Console.Read();
    }
}
